package com.deyuanyun.pic.pbf.controller;

import com.alibaba.fastjson.JSON;
import com.deyuanyun.pic.common.tool.Globals;
import com.deyuanyun.pic.common.tool.JXL;
import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.common.util.ajax.AjaxSupport;
import com.deyuanyun.pic.common.util.poi.ExcelUtil;
import com.deyuanyun.pic.common.util.web.Asserts;
import com.deyuanyun.pic.common.util.web.WebUtil;
import com.deyuanyun.pic.pbf.controller.dto.DefectInfoDTO;
import com.deyuanyun.pic.pbf.controller.dto.DefectSuggestVO;
import com.deyuanyun.pic.pbf.controller.dto.InspTaskQueryVO;
import com.deyuanyun.pic.pbf.domain.RepairTaskWorkload;
import com.deyuanyun.pic.pbf.service.DefectInfoService;
import com.deyuanyun.pic.pipe.controller.BaseController;
import com.deyuanyun.pic.settings.service.pipe.PipeLineService;
import com.deyuanyun.pic.settings.util.DownExcelUtil;
import com.deyuanyun.pic.wf.service.ProcessDefinitionService;
import com.google.common.base.Objects;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Nullable;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 *  缺陷维修建议controller
 *  @author axiao(xj08.dream@gmail.com)
 *  @date 2016-06-15
 *  @version 1.0
 *  Histroy: [修改人][时间][描述]
 */
@Controller
@RequestMapping("/pbf/suggestion")
public class DefectSuggestionController extends BaseController {

    @Autowired
    private DefectInfoService defectInfoService;

    @Autowired
    private ProcessDefinitionService processDefinitionService;

    @Autowired
    private PipeLineService pipeLineService;

    /**
     * 跳转到缺陷维修建议主页
     * @param modelMap
     * @return
     */
    @RequestMapping("/toSuggest.html")
    public String toSuggestPage(ModelMap modelMap) {
        modelMap.addAttribute("repairTypes", processDefinitionService.queryProcessDefinitionPbf());
        modelMap.addAttribute("lineList",pipeLineService.getLine());
        return "/pbf/repairAdvise/adviseList";
    }


    /**
     * 列表数据
     * @param defectSuggestVO
     * @param searchType 目前加这个参数的目的是为了方便前台绑定table的数据，为空的时候按照defectSuggestVO参数查询，为空的时候进行后台查询,不为空直接返回
     */
    @RequestMapping("/search.json")
    @ResponseBody
    public void searchList(final DefectSuggestVO defectSuggestVO, @RequestParam(value = "searchType", defaultValue = "") String searchType){

        if(StringUtils.isNotEmpty(searchType)) { //加这个代码的目的是方便前台table控件的数据绑定
            AjaxSupport.sendSuccessText("success", Collections.emptyList());
            return;
        }

        Collection<DefectInfoDTO> defectList = defectInfoService.queryBySuggestVO(defectSuggestVO);
        if(defectList != null) {
            final List<String> excludeDeIds =  defectSuggestVO.getExcludeDeIds();
            if (excludeDeIds != null && excludeDeIds.size() > 0) {
                //排除页面上不需要展示的缺陷信息,相同管道id和缺陷id才会排除
                defectList = Collections2.filter(defectList, new Predicate<DefectInfoDTO>() {
                    @Override
                    public boolean apply(@Nullable DefectInfoDTO input) {
                        if(input == null) {
                            return false;
                        }
                        if(excludeDeIds.contains(input.getDefectId()) &&
                                Objects.equal(defectSuggestVO.getPipeId(), input.getPipeId())) {
                            return false;
                        } else {
                            return true;
                        }
                    }
                });
            }
        }
        AjaxSupport.sendSuccessText("success", defectList);
    }

    /**
     * 导出缺陷列表excel
     * @param response
     */
    @RequestMapping("/exportExcel.json")
    @ResponseBody
    public void exportExcel(HttpServletResponse response, DefectSuggestVO defectSuggestVO, String taskName) throws IOException {
        String filePath = "/template/excl/pbf/defect_suggestion.xlsx";
        List<DefectInfoDTO> defectList = defectInfoService.queryBySuggestVO(defectSuggestVO);
        List<String[]> listSheet = JXL.toListFormVO(defectList, "yyyy-MM-dd");
        Integer beginRow = 4;
        Workbook workbook = ExcelUtil.initWorkbook(filePath, listSheet, beginRow - 2);//-2是因为删除了模板的头部两行
        String excelName =  defectSuggestVO.getPipeLineName()  +  taskName + "缺陷维修建议" + LocalDate.now().toString("yyyyMMdd") + ".xlsx";
        DownExcelUtil.fillWorkbookHead(workbook);
        WebUtil.setDownHeader(excelName);
        workbook.write(response.getOutputStream());
    }

    /**
     * 下载评价报告
     * @param response
     * @param pipeLineName 管道名称
     * @param taskName 检测任务名称
     */
    @RequestMapping("/downloadAppraise.json")
    @ResponseBody
    public void appraiseReport(HttpServletResponse response, String pipeLineName, String taskId, String taskName) throws  Exception {
        Asserts.assertTrue(StringUtils.isNotEmpty(taskId), "请输入检测任务id");
        List<Map<String, Object>> dataMap = defectInfoService.queryEvaluTaskAtta(taskId);
        if(dataMap.size() == 0 || dataMap == null) {
            AjaxSupport.sendFailText("error", "");
        }
        String nowDateStr = LocalDate.now().toString("yyyyMMdd");

        //当查询上来的附件为1时，不打包文件
        if(dataMap != null && dataMap.size() == 1) {
            Map<String, Object> map = dataMap.get(0);
            Object realNameObj = map.get("REALNAME");
            Object pathObj = map.get("PATH");
            Object fileType = map.get("FILETYPE");
            if(realNameObj != null && pathObj != null && fileType != null) {
                WebUtil.setDownHeader(pipeLineName + taskName + "缺陷评价报告" + nowDateStr +fileType.toString()); //下载名
                String fileUploadDir = Globals.getProperties("upload_file_dir");
                File file = new File(fileUploadDir + "/" + pathObj.toString());
                FileInputStream fis = null;
                OutputStream outputStream = null;
                try{
                    fis = new FileInputStream(new File(fileUploadDir + "/"+ pathObj.toString()));
                    outputStream =  response.getOutputStream();
                    byte[] buffer= IOUtils.toByteArray(fis);
                    outputStream.write(buffer, 0, buffer.length);
                } finally{
                    try {
                        fis.close();
                    } catch (Exception e) {
                    }
                    try {
                        outputStream.close();
                    } catch (Exception e) {
                    }
                }
                return;
            }
        }
        //打包下载评价报告
        WebUtil.setDownHeader(pipeLineName + taskName + "缺陷评价报告" + nowDateStr + ".zip"); //下载名
        defectInfoService.queryEvaluTaskAtta(response.getOutputStream(), dataMap);
    }

    @RequestMapping("/repairTaskWorkload.json")
    @ResponseBody
    public void repairTaskWorkload(String[] defectInfoId){
        RepairTaskWorkload repairTaskWorkload = defectInfoService.countWorkload(Arrays.asList(defectInfoId));
        AjaxSupport.sendSuccessText("success", repairTaskWorkload);
    }

    /**
     * 跳转到生成维修项目页面
     * @param defectId
     * @param modelMap
     * @return
     */
    @RequestMapping("/toGenerateRepair.html")
    public String repairProject(String[] defectId, ModelMap modelMap) {
        Asserts.assertTrue(defectId != null , "请选择至少一条缺陷信息");
        modelMap.addAttribute("defectList", JSON.toJSONString(defectId));//页面操作需要的缺陷id集合
        return "/pbf/repairAdvise/adviseProject";
    }

    /**
     * 根据管道id、起点绝对距离和终点绝对距离获取到检测任务
     * @param inspTaskQueryVO
     */
    @RequestMapping("/getTask.json")
    @ResponseBody
    public void queryTaskInfo(InspTaskQueryVO inspTaskQueryVO) {
        AjaxSupport.sendSuccessText("success", StringUtils.DATE, defectInfoService.queryTaskInfo(inspTaskQueryVO));
    }
}
